package com.imyuanma.qingyun.common.config;

import com.imyuanma.qingyun.common.exception.BaseException;
import com.imyuanma.qingyun.common.model.ECommonResultCode;
import com.imyuanma.qingyun.common.model.response.Result;
import com.imyuanma.qingyun.common.util.JsonUtil;
import com.imyuanma.qingyun.common.util.constants.CommonConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


/**
 * 异常处理
 * @author rookie
 *
 */
@Component
public class ExceptionHandler implements HandlerExceptionResolver {

    private Logger logger = LoggerFactory.getLogger(ExceptionHandler.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response, Object handler, Exception ex) {
        ModelAndView modelAndView = new ModelAndView();
        PrintWriter pw = null;
        try {
            logger.error("[全局异常处理] Exception URL={}", request.getRequestURL(), ex);
            response.setCharacterEncoding(CommonConstants.CHARSET);
            response.setContentType("application/json; charset=utf-8");
            pw = response.getWriter();
            Result result = null;
            if (ex instanceof BaseException) {
                result = Result.error(((BaseException) ex).getCode(), ((BaseException) ex).getInfo());
            } else {
                result = Result.error(ECommonResultCode.FAIL);
            }
            pw.write(JsonUtil.toJson(result));
        } catch (IOException e) {
            logger.error("[全局异常处理] 响应流写入异常", e);
        } catch (Exception e) {
            logger.error("[全局异常处理] 异常处理过程中发生异常!!!", e);
        } finally {
            try {
                if (pw != null) {
                    pw.close();
                }
            } catch (Exception e) {
                logger.error("[全局异常处理] 关闭PrintWriter异常", e);
            }
        }
        return modelAndView;
    }

}
